import 'dart:io';
import 'dart:typed_data';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_setting/pages/utils/app_utils.dart';
import 'package:video_setting/pages/utils/http_util.dart';
import 'package:video_setting/pages/utils/loading_util.dart';
import 'package:video_setting/pages/utils/toast_utils.dart';

class BaseApi {
  static late Dio _dio;
  // static initDio(String baseUrl, Function exitAppFunc, Function tokenExpireChargeFunc) {
  // ignore: always_declare_return_types
  static initDio(String baseUrl) async {
    var options = BaseOptions(
        baseUrl: baseUrl,

        /// 连接服务器超时时间，单位是毫秒.
        connectTimeout: 10000,

        /// 接收数据的总时限.
        receiveTimeout: 10000,

        /// [表示期望以那种格式(方式)接受响应数据。接受四种类型 `json`, `stream`, `plain`, `bytes`. 默认值是 `json`](https://github.com/flutterchina/dio/issues/30)
        responseType: ResponseType.json,

        /// 请求的Content-Type，默认值是[ContentType.json]. 也可以用ContentType.parse("application/x-www-form-urlencoded")
        contentType: Headers.jsonContentType,

        /// Http请求头.
        // headers: {'authorization': UserAgent.instance.getToken()?.isNotEmpty == true ? 'Bearer ' + UserAgent.instance.getToken().toString() : null});

        headers: null);

    _dio = Dio(options);

    // ByteData data = await rootBundle.load('assets/certificate/[certificateName].crt');
    // (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
    //   SecurityContext securityContext = new SecurityContext();
    //   securityContext.setTrustedCertificatesBytes(data.buffer.asUint8List());
    //   client = HttpClient(context: securityContext);
    //   return client;
    // };

    (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client) {
      client.badCertificateCallback = (X509Certificate cert, String host, int port) {
        return true;
      };
    };

    /// Cookie管理
    _dio.interceptors.add(CookieManager(CookieJar()));

    _dio.interceptors
      ..add(InterceptorsWrapper(onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
        return handler.next(options);
      }, onResponse: (Response response, ResponseInterceptorHandler handler) async {
        if (response.requestOptions.responseType == ResponseType.json) {
          //拦截错误码
          if (response.data['code'] == 500) {
            ToastUtil.show(response.data['msg']);
          } else if (response.data['code'] == 401) {
            ToastUtil.show(response.data['msg']);
            AppUtil.logout();

            return;
          }
        }
        return handler.next(response);
      }, onError: (DioError e, ErrorInterceptorHandler handler) {
        if (e.error == 'Http status error [403]') {
          ToastUtil.show('无访问权限');
        } else {
          ToastUtil.show('网络错误，请稍后重试!');
        }
      }))

      /// 添加 LogInterceptor 拦截器来自动打印请求、响应日志
      ..add(LogInterceptor(error: true, request: true, requestBody: true, requestHeader: false, responseHeader: false, responseBody: true));
  }

  static Future postFuture(String url, {Map<String, dynamic>? param, bool? isLoading = true}) async {
    if (isLoading == true) {
      LoadingUtil.showLoadingDialog();
    }
    var future = await HttpUtil(_dio).post(url, data: param);
    if (isLoading == true) {
      LoadingUtil.hidenLoadingDialog();
    }
    return future;
  }

  static Future getFuture(String url, {Map<String, dynamic>? queryParam}) async {
    return await HttpUtil(_dio).get(url, data: queryParam);
  }

  static Future postBodyOnly(String url, dynamic data) async {
    return await HttpUtil(_dio).postBodyOnly(url, data: data);
  }

  static Future postFormData(String url, FormData formData) async {
    return await HttpUtil(_dio).postFormData(url, data: formData);
  }

  static Future uploadImage(String url, XFile xFile) async {
    var path = xFile.path;
    var name = path.substring(path.lastIndexOf('/') + 1, path.length);
    final bytes = Uint8List.view((File(path).readAsBytesSync()).buffer);
    var formData = FormData.fromMap({'file': await MultipartFile.fromFile(path, filename: name)});

    return await HttpUtil(_dio).postFormData(url, data: formData);
  }

  static Future postFutureByte(String url, {Map<String, dynamic>? param}) async {
    return await HttpUtil(_dio).postFetchByte(url, data: param, options: Options(responseType: ResponseType.bytes));
  }

  /// 刷新header中的token
  // static void refreshHeaderToken() {
  //   if (UserAgent.instance.getToken()?.isNotEmpty == true) {
  //     _dio.options.headers['authorization'] = 'Bearer ' + UserAgent.instance.getToken().toString();
  //   }
  // }
}
